<template>
  <div class="orders-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索订单号/用户名"
              style="width: 200px; margin-right: 10px"
            />
            <el-select v-model="statusFilter" placeholder="订单状态" style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="待付款" value="待付款" />
              <el-option label="已付款" value="已付款" />
              <el-option label="已发货" value="已发货" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table :data="filteredOrders" style="width: 100%">
        <el-table-column prop="order_no" label="订单号" width="140" />
        <el-table-column label="商品信息" width="300">
          <template #default="scope">
            <div v-for="item in scope.row.items" :key="item.product_id" class="product-info">
              {{ item.product_name }} x {{ item.quantity }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="receiver_name" label="收货人" width="90" />
        <el-table-column prop="receiver_phone" label="联系电话" width="120" />
        <el-table-column prop="total_amount" label="订单金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.total_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="150" />
        <el-table-column prop="pay_time" label="支付时间" width="150" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <!-- <el-button 
              type="primary" 
              link
              @click="handleView(scope.row)"
            >
              
            </el-button> -->
            <el-button 
              type="primary" 
              link 
              v-if="scope.row.status === '待付款'"
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
            <el-button 
              type="danger" 
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getOrders, deleteOrder, updateOrderStatus } from '@/api/order'
import { ElMessage, ElMessageBox } from 'element-plus'

const orders = ref([])
const searchQuery = ref('')
const statusFilter = ref('')

// 获取订单列表
const fetchOrders = async () => {
  try {
    const response = await getOrders()
    if (response.code === 200) {
      // 处理商品信息字符串
      orders.value = response.data.map(order => ({
        ...order,
        items: order.items ? order.items.split(';').map(item => {
          const [product_name, quantity] = item.split(':')
          return {
            product_name,
            quantity: parseInt(quantity)
          }
        }) : []
      }))
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 过滤订单
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    const matchQuery = searchQuery.value ? 
      (order.order_no.includes(searchQuery.value) || 
       order.user_name.includes(searchQuery.value)) : true
    const matchStatus = statusFilter.value ? 
      order.status === statusFilter.value : true
    return matchQuery && matchStatus
  })
})

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '待付款': 'warning',
    '已付款': 'success',
    '已发货': 'primary',
    '已完成': 'info',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 查看订单
//const handleView = (order) => {
  // 实现查看订单详情的逻辑
  // console.log('查看订单:', order)
//}

// 取消订单
const handleCancel = (order) => {
  ElMessageBox.confirm(
    '确定要取消这个订单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await updateOrderStatus(order.order_no, { status: '已取消' })
      if (response.code === 200) {
        ElMessage.success('订单已取消')
        fetchOrders()
      } else {
        ElMessage.error(response.message || '取消失败')
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消失败')
    }
  }).catch(() => {})
}

// 删除订单
const handleDelete = (order) => {
  ElMessageBox.confirm(
    '确定要删除这个订单吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteOrder(order.order_no)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchOrders()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除订单失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.product-info {
  margin: 2px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.2;
}
</style> 